package com.bnz.servlet;

import cn.hutool.core.util.StrUtil;
import com.bnz.pojo.Cart;
import com.bnz.pojo.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {

    //1. 根据请求参数调用不同的方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.1 得到请求参数
        String cmd = req.getParameter("cmd");
        //1.2 根据参数调用不同的方法
        if (StrUtil.isNotBlank(cmd)){
            if ("add".equals(cmd)){         //1. 添加购物车
                add(req,resp);
            }
            if ("remove".equals(cmd)){      //2. 移除购物车
                remove(req,resp);
            }
            if ("clear".equals(cmd)){       //3. 清空购物车
                clear(req,resp);
            }
        }

    }


    //2. 添加购物车
    private void add(HttpServletRequest req, HttpServletResponse resp) throws  ServletException, IOException {
        //2.1 得到商品id
        String pid = req.getParameter("pid");
        //2.2 得到商品列表信息
        ServletContext servletContext = this.getServletContext();
        Map<String, Product> products = (Map<String, Product>) servletContext.getAttribute("products");
        //2.3 根据商品id得到商品
        Product product = products.get(pid);
        //2.4 处理购物车
        //2.4.1 得到session对象
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        //2.4.2 判断是否是第一次购物,如果是就构造一个购物车
        if (cart == null){
            cart = new Cart();
        }
        //2.4.3 添加商品到购物车
        cart.add(product);
        //2.4.4 添加购物车到session中
        session.setAttribute("cart",cart);
        //2.4.5 跳转到购物页面列表
        resp.sendRedirect("/cart_list.jsp");
    }

    //3. 移除购物车
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws  ServletException, IOException {
        //3.1 获取商品id
        String pid = req.getParameter("pid");
        //3.2 得到购物车
        //3.2.1 得到session
        HttpSession session = req.getSession();
        //3.2.2. 从session中取出购物车
        Cart cart = (Cart) session.getAttribute("cart");
        //3.2.3 从购物车中移除商品
        cart.remove(pid);

        //3.2.4 跳转到购物车列表页面
        resp.sendRedirect("/cart_list.jsp");
    }

    //4. 清空购物车
    private void clear(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //4.1 得到购物车
        //4.1.1 得到session对象
        HttpSession session = req.getSession();
        //4.1.2 从session中取出购物车
        Cart cart = (Cart) session.getAttribute("cart");
        //4.2 清空购物车
        cart.clear();
        //4.3 跳转到购物车列表页表
        resp.sendRedirect("/cart_list.jsp");
    }

}
